import decimal

from werkzeug.security import generate_password_hash, check_password_hash
from sqlalchemy import Integer, String, DECIMAL, Enum, ForeignKey
from sqlalchemy.orm import mapped_column, relationship

from takeaway import const
from takeaway.ext import db


class User(db.Model):
    id = mapped_column(Integer, primary_key=True)
    nickname = mapped_column(String, nullable=False)
    phone = mapped_column(String(11), unique=True, nullable=False)
    gender = mapped_column(Enum(const.Gender), nullable=False)
    avatar = mapped_column(String, nullable=True)
    balance = mapped_column(DECIMAL, nullable=False, default=decimal.Decimal)
    password_hash = mapped_column("password", String(128), nullable=False)

    addresses = relationship("Address", back_populates="user")

    @property
    def password(self):
        return self.password_hash

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def validate_password(self, password):
        return check_password_hash(self.password_hash, password)


class Address(db.Model):
    """
        收货地址
    """
    id = mapped_column(Integer, primary_key=True)
    name = mapped_column(String, nullable=False)
    phone = mapped_column(String(11), unique=True, nullable=False)
    place = mapped_column(String, nullable=False)
    user_id = mapped_column(Integer, ForeignKey("user.id"))

    user = relationship(User, back_populates="addresses")
